package com.guoning.office_system.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Token的工具类
 * @author ganwh
 * @since 2020-3-10
 *
 */
public class TokenTools {

    /**
     * 生成token放入session
     * @param request
     * @param object
     */
    public static String createToken(HttpServletRequest request, Object object){
//        String token = TokenProccessor.getInstance().makeToken();
        String token = UUID.randomUUID().toString();
        request.getSession().setAttribute(token, object);
        return token;
    }

    /**
     * 移除token
     * @param request
     * @param token
     */
    public static void removeToken(HttpServletRequest request,String token){
        request.getSession().removeAttribute(token);
    }

    /**
     * 判断请求参数中的token是否和session中一致
     * @param request
     * @param tokenClientkey
     * @param tokenServerkey
     * @return
     */
    public static boolean judgeTokenIsEqual(HttpServletRequest request,String tokenClientkey,String tokenServerkey){
        String token_client = request.getParameter(tokenClientkey);
        if(StringUtils.isEmpty(token_client)){
            return false;
        }
        String token_server = (String) request.getSession().getAttribute(tokenServerkey);
        if(StringUtils.isEmpty(token_server)){
            return false;
        }

        if(!token_server.equals(token_client)){
            return false;
        }

        return true;
    }

}